'use strict';

function InsertString(t, c, n) {
	var r = new Array();
	for (var i = 0; i * 2 < t.length; i++) {
		r.push(t.substr(i * 2, n));
	}
	return r.join(c);
}

function FillString(t, c, n, b) {
	if ((t == "") || (c.length != 1) || (n <= t.length)) {
		return t;
	}
	var l = t.length;
	for (var i = 0; i < n - l; i++) {
		if (b == true) {
			t = c + t;
		} else {
			t += c;
		}
	}
	return t;
}

function HexToSingle(t) {
	t = t.replace(/\s+/g, "");
	if (t == "") {
		return "";
	}
	if (t == "00000000") {
		return "0";
	}
	if ((t.length > 8) || (isNaN(parseInt(t, 16)))) {
		return "Error";
	}
	if (t.length < 8) {
		t = FillString(t, "0", 8, true);
	}
	t = parseInt(t, 16).toString(2);
	t = FillString(t, "0", 32, true);
	var s = t.substring(0, 1);
	var e = t.substring(1, 9);
	var m = t.substring(9);
	e = parseInt(e, 2) - 127;
	m = "1" + m;
	if (e >= 0) {
		m = m.substr(0, e + 1) + "." + m.substring(e + 1)
	} else {
		m = "0." + FillString(m, "0", m.length - e - 1, true)
	}
	if (m.indexOf(".") == -1) {
		m = m + ".0";
	}
	var a = m.split(".");
	var mi = parseInt(a[0], 2);
	var mf = 0;
	for (var i = 0; i < a[1].length; i++) {
		mf += parseFloat(a[1].charAt(i)) * Math.pow(2, -(i + 1));
	}
	m = parseInt(mi) + parseFloat(mf);
	if (s == 1) {
		m = 0 - m;
	}
	return m;
}

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	
	const t = event.queryStringParameters.t;
	const p = event.queryStringParameters.p;
	const o = event.queryStringParameters.o;
	const n = event.queryStringParameters.n;
	const imei=event.queryStringParameters.imei;
	const dbJQL = uniCloud.databaseForJQL({
		event,
		context
	})
	
	const data={
		temp:HexToSingle(t),
		ph:HexToSingle(p),
		odo:HexToSingle(o),
		nh4:HexToSingle(n),
		imei:imei
	}
	console.log(data)
	await dbJQL.collection("gf-jc").add(data)
	//返回数据给客户端
	return ''
};